package com.fuxin.app.error;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.thoughtworks.xstream.core.BaseException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author fuxin
 * @date 2019/3/1 10:06
 * @description
 */
@ControllerAdvice
public class GlobalExceptionHandler {


	@ExceptionHandler(value = BasicException.class)
	public ModelAndView errorHandle(HttpServletRequest request, BasicException exception
	, HttpServletResponse response){ // 处理方法参数的异常类型

		ExceptionEntity entity = new ExceptionEntity();
		entity.setMessage(exception.getMessage());
		entity.setPath(request.getRequestURI());
		entity.setCode(exception.getCode());
		entity.setError(exception.getClass().getSimpleName());
		if(!request.getHeader("accept").contains("application/json")
		|| (request.getHeader("X-Requested-With") != null)
			&& request.getHeader("X-Requested-With").contains("XMLHttpRequest")){
			ModelAndView model = new ModelAndView("error");
			model.addObject("exception",entity);
			return model;
		}else{
			try{
				response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
				response.setCharacterEncoding(request.getCharacterEncoding());
				response.setHeader("Content-Type", "application/json");
				response.getWriter().write(JSON.toJSONString(entity));
			}catch (Exception e){
				e.printStackTrace();
			}
			return null;
		}
	}

}
